import React, { PureComponent } from 'react';
import { connect } from 'dva';
import '@ant-design/compatible/assets/index.css';
import {Modal, Button, Table, message, Form, Space, Tooltip, Typography, Input, Select, Card, Row, Col} from 'antd';
import styles from '../../../components/common/PateoTable/TableList.less';
import { FormInstance } from 'antd/lib/form';
import { transferOption } from "@/utils/common";
import RuleModal from '../commonModal/ruleModal';

const FormItem = Form.Item;
const mapStateToProps = (state: any) => ({
  // loading: state.loading.effects['audienceList/putObjWithRes'],
  loading: state.loading.effects['http/getData'],
  user: state?.menu?.userProfile
});
class LockModal extends PureComponent<any, any> {
  formRef = React.createRef<FormInstance>();
  constructor(props: any) {
    super(props);
    this.state = {
      loading: false,
      ruleModalVisible: false,
      ruleOptiosns: [],
    };
  }

  componentDidMount() {
    this.props.onRef(this);
  }

  componentDidUpdate(prevProps: any) {
    const { vehicleId, modalVisible, dispatch } = this.props
    if (!modalVisible) {
      return false
    }
    if (modalVisible && modalVisible !== prevProps.modalVisible) {
      this.formRef.current?.resetFields()
      this.initRuleData()
    }
  }

  initRuleData = () => {
    const tempParam = {
      pageNo: 1,
      pageSize: 9999,
      ruleStatus: 1,
      // tenantCode: 'MATC',
    }
    this.props.dispatch({
      type: 'http/postObj',
      payload: {
        url: '/commodity/vehicle/warnRule/page',
        ...tempParam,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          res.data.rows && this.formatRulesList(res.data.rows)
        } else {
          message.error('获取告警规则数据失败')
        }
      }
    })
  }

  formatRulesList = (list: []) => {
    let tempList: any[] = []
    list.forEach((item: any) => {
      tempList.push({
        label: item.warnRuleName,
        value: item.sid,
      })
    })
    this.setState({
      ruleOptiosns: tempList
    })
  }

  close = () => {
    const { closeModal } = this.props;
    closeModal();
  };

  handleLock = () => {
    let alarmRule = this.formRef.current?.getFieldValue('alarmRule')
    if (!alarmRule) {
      message.error('请选择车机告警规则')
      return false
    }
    this.formRef.current?.submit();
    // this.formRef.current?.getFieldValue('alarmRule');
  }

  ok = () => {
    //  提交表单
    let warnRuleId = this.formRef.current?.getFieldValue('alarmRule')
    const { dispatch, vehicleId, user, refreshPage } = this.props;
    dispatch({
      type: 'http/postDataWithRes',
      payload: {
        url: `/commodity/vehicle/monitor/lock/${vehicleId}`,
        warnRuleId,
        operator: user?.accountName,
      },
      callback: (res: any) => {
        if (res.statusCode === '0') {
          message.success('操作成功')
        }
        this.close();
        refreshPage && refreshPage();
      }
    })
  }

  addRule = () => {
    this.setState({
      ruleModalVisible: true
    })
  }

  closeRuleModal = () => {
    this.setState({
      ruleModalVisible: false,
    });
  }

  refreshRulesOptions = () => {
    this.initRuleData()
  }

  render() {
    const { modalVisible } = this.props;
    const { ruleModalVisible, ruleOptiosns } = this.state

    const footer = (
      <div>
        <Button size="small" onClick={this.close}>
          取消
        </Button>
        <Button size="small" onClick={this.handleLock} type="primary">
          确认
        </Button>
        {/* <Button size="small" loading={loading} onClick={this.handleLock} type="primary">
          保存
        </Button> */}
      </div>
    );

    const formItemLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 12 },
        md: { span: 16 },
      },
    };

    return (
      <Modal
        title="锁车"
        // style={{ width: '800px' }}
        width={800}
        bodyStyle={{ maxHeight: '700px' }}
        footer={footer}
        visible={modalVisible}
        onCancel={this.close}
      >
        <Form
          style={{ marginTop: 12 }}
          ref={this.formRef}
          onFinish={this.ok}
          layout="vertical"
        >
          <Form.Item label="车机告警规则">
            <Space>
              <Form.Item
                label="车机告警规则"
                name="alarmRule"
                noStyle
                // {...formItemLayout}
                rules={[{ required: true, message: '' }]}
              >
                <Select 
                  allowClear
                  style={{ width: 320, marginLeft: '2em' }}
                  placeholder="请选择" >
                    { transferOption(ruleOptiosns,["value","label"])}
                  </Select>
              </Form.Item>
              <Typography>
                <Button type="link" onClick={this.addRule}>新建规则</Button>
              </Typography>
            </Space>
          </Form.Item>
          <div style={{color: '#ff0000'}}>*注意：锁车时，必须发送车机告警，且为霸屏提醒</div>
        </Form>
        <RuleModal 
          onRef={(val: any) => (this.ruleModal = val)}
          modalVisible={ruleModalVisible}
          closeModal={this.closeRuleModal}
          refreshPage={this.refreshRulesOptions}
        />
      </Modal>
    )
  }
}
export default connect(mapStateToProps)(LockModal);
